package com.optitronics.controllers;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.optitronics.beans.SystemProperties;
import com.optitronics.util.OptitronicsConstants;

@RequestMapping("/systemproperties")
@Controller
@SessionAttributes("systemProperty")
public class SystemPropertiesController {

	@RequestMapping(method = RequestMethod.GET)
	public String list(@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "size", required = false) Integer size, Model uiModel) {
		if (page != null || size != null) {
			int sizeNo = size == null ? OptitronicsConstants.PAGE_SIZE : size.intValue();
			uiModel.addAttribute("systemproperties", SystemProperties.findSystemPropertiesEntries(page == null ? 0
					: (page.intValue() - 1) * sizeNo, sizeNo));
			float nrOfPages = (float) SystemProperties.countSystemPropertieses() / sizeNo;
			uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
					: nrOfPages));
		} else {
			uiModel.addAttribute("systemproperties", SystemProperties.findAllSystemPropertieses());
		}
		return "systemproperties/list";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String update(@ModelAttribute("systemProperty") SystemProperties systemProperties,
			BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest, SessionStatus status) {
		if (bindingResult.hasErrors()) {
			uiModel.addAttribute("systemProperty", systemProperties);
			return "systemproperties/update";
		}
		status.setComplete();
		systemProperties.merge();
		return "redirect:/systemproperties/";
	}

	@RequestMapping(value = "/{propertyKey}/edit", method = RequestMethod.GET)
	public String updateForm(@PathVariable("propertyKey") String propertyKey, Model uiModel) {
		uiModel.addAttribute("systemProperty", SystemProperties.findSystemProperties(propertyKey));
		return "systemproperties/update";
	}

}
